<?php

	if (isset($_GET['name']) && isset($_GET['position']) && isset($_GET['salary']))
	{
		$username = $_SESSION['username'];
		$name = $_GET['name'];
		$position = $_GET['position'];
		$salary = $_GET['salary'];
		$playerCash = getPlayerCash();
		
		if ($salary > $playerCash)
		{
			echo "You do not have enough money to hire $name as a $position. <a href='index.php?view=employees'>Back</a>";
		} else {
			$playerCash = $playerCash - $salary;
			$owner_id = mysql_result(mysql_query("SELECT id FROM users WHERE username='$username'"), 0);
			$occupation_id = mysql_result(mysql_query("SELECT id FROM employee_types WHERE name='$position'"), 0);
			$hospital_id = mysql_result(mysql_query("SELECT id FROM hospitals WHERE owner_id=$owner_id"), 0);
			mysql_query("UPDATE users SET cash=$playerCash WHERE username='$username'");
			mysql_query("INSERT INTO employees (name, occupation_id, hospital_id) VALUES ('$name', '$occupation_id', '$hospital_id')");
			echo "$name hired for \$$salary. You now have \$$playerCash";
		}
	} else {

	echo "<fieldset>";
	echo "<legend><b>Hire Employees</b></legend><br />";
	echo "<table width='400' cellpadding='10'><center>
	<tr><th> Name </th><th> Position </th><th> Salary </th><th> </th></tr>";
	for ($i = 0; $i < mysql_num_rows(mysql_query("SELECT name FROM employee_types")); $i++)
	{
		$result = mysql_query("SELECT name,salary FROM employee_types");
		$avg_salary = mysql_result($result, $i, "salary");
		$salary = rand($avg_salary + 0.2 * $avg_salary,  $avg_salary - 0.2 * $avg_salary);
		$position = mysql_result($result, $i, "name");
		$name = getRandomName();
		echo "<tr><td> $name </td><td> $position </td><td> \$$salary </td><td> <a href='index.php?view=hireemployees&amp;name={$name}&amp;position={$position}&amp;salary={$salary}'>Hire</a> </td></tr>";
	}
	echo "<tr><td colspan='3' align='center'><input type='submit' value='Buy' /></td></tr></center></table></center></form><br />";
	echo "<a href='index.php?view=employees'>Back to Employees</a>";
	echo "<br /></fieldset>";
	}
	
	function getRandomName()
	{
		$fn_randMax = mysql_num_rows(mysql_query("SELECT id FROM r_first_names"));
		$ln_randMax = mysql_num_rows(mysql_query("SELECT id FROM r_last_names"));
		$fn_rand = rand(1,$fn_randMax);
		$ln_rand = rand(1,$ln_randMax);
		$fnresult = mysql_query("SELECT name FROM r_first_names WHERE id='$fn_rand'");
		$lnresult = mysql_query("SELECT name FROM r_last_names WHERE id='$ln_rand'");
		$fn = mysql_result($fnresult, 0);
		$ln = mysql_result($lnresult, 0);
		return $fn." ".$ln;
	}
	
	function getPlayerCash()
	{
		$username = $_SESSION['username'];
		$result = mysql_query("SELECT cash FROM users WHERE username='$username'");
		$cash = mysql_result($result, 0);
		if ($cash != NULL) {
			return $cash;
		} else { return 0; }
	}

?>